

import Tkinter
from Tkinter import *
from ttk import *
from PIL import Image, ImageTk
from tkMessageBox import showerror

import urllib2
import tempfile
import os
import sys

import vkontakte

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
opener.addheaders = [(k, v) for k, v in vkontakte.HEADERS.items()]
urllib2.install_opener(opener)


def show_error(msg):
	if not Tkinter._default_root:
		r = Tk()
		r.withdraw()
	showerror('evlum error', msg)


def ask_captcha(url):
	
	file = open(tempfile.mkstemp()[1], "wb")
	#print file.name
		
	file.seek(0)
	for i in urllib2.urlopen(url):
		file.write(i)
	file.flush()
		
	root = Toplevel()
	root.protocol("WM_DELETE_WINDOW", root._root().destroy)
	root.title('evlum')
	
	Label(root, text="Type in the captcha...").pack()
	
	image = Image.open(file.name)
	photo = ImageTk.PhotoImage(image)
	#photo = PhotoImage(file=file.name)
		
	label = Label(root, image=photo)
	label.image = photo # keep a reference!
	label.pack()
		
	entr = Entry(root)
	entr.focus_set()
	entr.bind('<Return>', lambda evt: btn.invoke())
	entr.pack()
		
	def _on_ok():
		result[0] = entr.get()
		print 'destroying'
		root.destroy()
	btn = Button(root, text="ok", command=_on_ok)
	btn.pack(fill="x")
		
	result = {0: None}
	try:
		while root.winfo_exists():
			root.update()
	except TclError:
		pass
	
	file.close()
	return result[0]



class GUI(Tk):
	def __init__(self, search_cb):
		Tk.__init__(self)
		#self.protocol("WM_DELETE_WINDOW", sys.exit)
		self.title('evlum - 1.0 BETA 2')
		self.enabled = True
				
		def cb():
			if self.enabled:
				got = entr.get()
				if not got: return
				search_cb(got)
				entr.delete(0, END)
		
		entr = Entry(self)
		entr.focus_set()
		entr.bind('<Return>', lambda evt: cb())
		entr.pack(side='left', expand='true', fill='x')
		
		
		self.btn = Button(self, text="Search", command=cb)
		self.btn.pack(side='left', expand='true', fill='x')
	
	
	def enable(self):
		print '\tenabling gui'
		self.enabled = True
		self.btn.config(state='active')
		
	def disable(self):
		print '\tdisabling gui'
		self.enabled = False
		self.btn.config(state='disabled')

		
	
		
		
		
		
		
		





